<?php
/************************FoxPHP威客系统************************/
/*                                                            */
/*  FoxPHP.Com (C)2006-2016 FoxPHP Inc.                       */
/*  This is NOT a freeware, use is subject to license terms   */
/*  FoxPHP威客系统是商业软件,使用于商业用途请购买授权         */
/*  V3.0 2016.3                                               */
/*  foxphp@aliyun.com                                         */
/*  http://www.foxphp.com                                     */
/*                                                            */
/**************************************************************/

namespace Upload\Model;
use Think\Model;
use \Org\Util\String;
//上传文件 
class FileModel extends Model {
	
	public $isimage=false; //是否图形
	
	public $uploadnumber=5; //上传数量
	
	//开始上传  0 附件 1 图形
	public function StartUpload($filetype=0){

		if(!$_FILES['file']['size']){
			$this->error='对不起!没有文件上传!';
			return false;
		}
		
		//未定义5个暂停上传
		if($filetype==1){
			$isusecount=$this->token(false)->where(" uid=$this->uid AND isuse=0 AND isimage=1")->count();
		}else{
			$isusecount=$this->token(false)->where(" uid=$this->uid AND isuse=0 AND isimage=0")->count();
		}
		if($isusecount>=$this->uploadnumber){
			$this->error='对不起!您上传数量已超!';
			return false;
		}
		
		$upload = new \Think\Upload();
		
		//检查文件类型
		$fileform=$this->CheckFileType();
		if(!$fileform){
			return false;
		}
		
		if(!is_dir(C('S_UPLOAD_DIR'))) {
			@mkdir(C('S_UPLOAD_DIR'),0777);
			WriteFile(C('S_UPLOAD_DIR').'/index.html','');
		}
		
		$newfilepath=$this->FilePath(C('S_UPLOAD_DIR'),$fileform);
		$upload->rootPath = $newfilepath; // 设置附件上传目录
		
		$times =@date("YmdHis");
		$newfilename=RandomText(8,1);
		$upload->saveName=$newfilename.$times;
		$upload->subName=$this->SavePath();
		
		if($filetype==1 && $this->isimage){
			//图形
			$upload->exts =explode(',',C('uploadphototype'));// 设置图片上传类型
			$upload->maxSize = intval(C('oneimageuploadsize')) ;// 设置图片上传大小
		}else{
			//附件
			$upload->exts = explode(',',C('uploadfiletype'));// 设置附件上传类型
			$upload->maxSize = intval(C('onefileuploadsize')) ;// 设置附件上传大小
		}
		
		$info = $upload->upload();
		if(!$info){
			$this->error=$upload->getError();
			return false;
		}else{
			//不销毁令牌
			$this->isunsettoken=false;
			//上传成功
			$name='';
			$_POST['name']=$_FILES['file']['name'];
			$filename=String::msubstr(I('post.name'),0,60,C('S_CHARSET'),false);
			$newnamearr=explode('.',$filename);
			if(!empty($newnamearr[0])){
				$name=$newnamearr[0];
			}
			
			$postarray=array(C('TOKEN_NAME')=>$_POST[C('TOKEN_NAME')],'uid'=>$this->uid,'filename'=>$filename,'name'=>$name,'filepath'=>$upload->rootPath.$info['file']['savepath'].$info['file']['savename'],'dateline'=>NowTime(),'filetype'=>$info['file']['type'],'filesize'=>intval($info['file']['size']));

			//处理缩图
			if($this->isimage){
							
				$image = new \Think\Image();
				
				$image->open($upload->rootPath.$info['file']['savepath'].$info['file']['savename']);
				
				$width = $image->width();
				$height = $image->height(); 

				$filethumbname=$upload->rootPath.$info['file']['savepath'].$upload->saveName.'_thumb.'.$fileform;
				
				//比例缩图
				$image->thumb(C('thumbwidth'),C('thumbheight'))->save($filethumbname);
				
				//水印	
				if($width>=intval(C('watermarkminimum')) && $height>=intval(C('watermarkminimum'))){
					$image->open($filethumbname);
					if(C('blackwatermark')){
						$nowtime=@date("Y/m/d H:i:s");
						$text=str_replace('{username}',$this->username,C('watermarkname'));
						$text=str_replace('{time}',$nowtime,$text);
						$image->text($text,FOXPHP_PATH.C('sitefont'),12,'#000000',\Think\Image::IMAGE_WATER_SOUTHEAST);
					}
					
					if(C('watermarklogo')){
						
						$image->water(FOXPHP_PATH.C('watermarklogopath'),intval(C('watermarklogoposition')),intval(C('watermarktransparent')));
					}
					
					$image->thumb(C('thumbwidth'),C('thumbheight'))->save($filethumbname);
				}

				
				$image->open($upload->rootPath.$info['file']['savepath'].$info['file']['savename']);
				//裁剪方形
				$filecutname=$upload->rootPath.$info['file']['savepath'].$upload->saveName.'_cut.'.$fileform;
				$image->thumb(C('screenshotwidth'),C('screenshotheight'),\Think\Image::IMAGE_THUMB_CENTER)->save($filecutname);
				

				$postarray=array_merge(array('thumb'=>$filethumbname,'thumbcut'=>$filecutname),$postarray);
			}
			
			if($filetype==1 && $this->isimage){
				$postarray['isimage']=1;
			}

			if ($this->token(false)->create($postarray)){
				if($id=$this->token(false)->add()){
					$result=array('id'=>$id,'type'=>'.'.$fileform,'filename'=>$info['file']['savename'],'originalname'=>$filename,'filepath'=>$upload->rootPath.$info['file']['savepath'].$info['file']['savename'],'size'=>intval($info['file']['size']));
					if($filetype==1 && $this->isimage){
						$result=array_merge(array('thumb'=>$filethumbname,'thumbcut'=>$filecutname),$result);
					}
					return $result;
				}
			}
			$this->error=$this->getError();
			return false;
		}
	}
	// 取消使用文件
	function UnUseFile($uid,$oid){
		$this->token(false)->where(" uid=$uid AND oid =$oid")->save(array('isuse'=>0));
	}

	//使用文件
	function UseFile($type='tid',$id=0){
		
		$post['isuse']=1;
		$where=' AND isuse=0 ';
		if($id && $type){
			$post[$type]=$id;
			$where=" AND isuse=1 AND $type=$id ";
		}
		
		//未使用
		$filearray=$this->token(false)->where(" uid=$this->uid AND isuse=0 ")->field('fid,isimage')->select();

		if(!empty($filearray)){
			
			//更新图形
			$useimagecount=$this->token(false)->where(" uid=$this->uid AND isimage=1 $where ")->count();
			$this->UpdateUseFile($post,$filearray,$useimagecount,1);
			
			//更新文件
			$usefilecount=$this->token(false)->where(" uid=$this->uid AND isimage=0 $where ")->count();
			$this->UpdateUseFile($post,$filearray,$usefilecount);
			
			return true;
		}
		
	}
	
	//更新使用文件
	function UpdateUseFile($post,$filearray,$usecount,$type=0){
		
		if($this->uploadnumber>$usecount){
			$updatenumber=$this->uploadnumber-$usecount;
			$fid='';
			$fidcount=0;
			foreach($filearray as $key=>$value){
				if(!empty($value['fid'])){
					if($value['isimage']==$type){
						$fidcount++;
						if($fid){
							$fid.=','.$value['fid'];
						}else{
							$fid=$value['fid'];
						}
						
						if($fidcount>=$updatenumber){
							break;
						}
					}
				}
			}

			if($fid){
				$this->token(false)->where(" uid=$this->uid AND isuse=0 AND isimage=$type AND fid IN($fid)")->save($post);
			}
		}
	}
	
	//获取未定义文件
	function UndefinedUpload($type=0){
		$field='fid,uid,filename,filesize,thumb';
		if($type){
			$sqlimage=" uid=$this->uid AND isimage=1 ";
			$field.=',filepath';
		}else{
			$sqlimage=" uid=$this->uid AND isimage=0 ";
		}
		
		//数据类型
		$tid=intval($_GET['tid']);
		$sid=intval($_GET['sid']);
		if($tid>0){
			//任务发布
			$sqlimage.=" AND tid=$tid OR isuse=0 AND ".$sqlimage;
		}elseif($sid>0){
			//服务
			$sqlimage.=" AND sid=$sid OR isuse=0 AND ".$sqlimage;
		}else{
			$sqlimage.=" AND isuse=0 ";
		}
		
		return $this->token(false)->where($sqlimage)->field($field)->order('isuse desc')->limit($this->uploadnumber)->select();
	}
	
	//获取已定义附件
	function GetUploadFile($type='tid',$id=0){
		$id=intval($id);
		return $this->token(false)->where(" $type=$id AND isuse=1 AND isimage=0 ")->select();
	}
	
	function FilePath($dir,$filetype){

		$dir1 = @gmdate('Ym');
		$dir2 = @gmdate('j');
		
		$ymdir=$dir.'/'.$dir1;

		if(!is_dir($ymdir)) {
			@mkdir($ymdir,0777);
			WriteFile($ymdir.'/index.html','');
		}
		$jdir=$ymdir.'/'.$dir2;
		if(!is_dir($jdir)){
			@mkdir($jdir,0777);
			WriteFile($jdir.'/index.html','');
		}
		return $ymdir.'/';
	}
	
	function SavePath(){
		return @gmdate('j');
	}
	
	//删除上传
	public function DeleteUpload($id=0){
		 
		if($id){
			$file=$this->token(false)->where(" fid=$id AND uid=$this->uid")->find();
			if(!empty($file['fid'])){
				$this->token(false)->where(" fid=$id AND uid=$this->uid ")->delete();
				DelFile(FOXPHP_PATH.'/'.$file['filepath']);
				if(!empty($file['thumb'])){
					DelFile(FOXPHP_PATH.'/'.$file['thumb']);
				}
				if(!empty($file['thumbcut'])){
					DelFile(FOXPHP_PATH.'/'.$file['thumbcut']);
				}
				return true;
			}
		}
		
		$this->error='对不起!该文件不存在!';
		return false;
	}
	
	public function CheckFileType(){

		//开启文件类型检查
		$fileform=GetFileForm($_FILES['file']['name']); 
		if(C('fileinfomime')){
			$fileinfomime=@GetFileInfoMIME($_FILES['file']['tmp_name']);
			
			$upload_info=C('S_UPLOAD_FILETYPE');

			if(in_array($fileform,array('jpg','gif','png'))){
				$fileheader=GetFileHeader($_FILES['file']['tmp_name']);
				$fileheadernum=array('jpg'=>255216,'gif'=>7173,'png'=>13780);
				if($fileinfomime==$upload_info[$fileform] && $fileheader==$fileheadernum[$fileform]){
					$this->isimage=true;
					return $fileform;
				}
			}else{
				if($fileinfomime==$upload_info[$fileform]){
					return $fileform;
				}
			}
			$this->error='对不起!该文件类型系统暂时不支持!';
			return false;
		}else{
			return $fileform;
		}

	}
}

?>